package cn.edu.sdjzu.xg2121.controller;

import cn.edu.sdjzu.xg2121.domain.University;
import cn.edu.sdjzu.xg2121.exception.BysjException;
import cn.edu.sdjzu.xg2121.service.UniversityService;
import cn.edu.sdjzu.xg2121.util.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/UniversityCreate.ctl")
public class UniversityUpdateCtl extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //创建JSON对象message_jsonObj,以便往前端响应信息
        JSONObject message_jsonObj = new JSONObject();
        //设置响应字符编码为UTF-8
        response.setContentType("application/json;charset=UTF-8");
        //将request body转换为JSON子串
        String req_jsonStr = JSONUtil.getJSON(request);
        JSONObject req_json_Obj = JSON.parseObject(req_jsonStr);
        //如果请求body为空
        if (req_json_Obj == null){
            message_jsonObj.put("message","未收到请求信息");
            response.getWriter().println(message_jsonObj);
            return;
        }
        try {
            University university = JSON.parseObject(req_jsonStr,University.class);
            String a = UniversityService.getInstance().update(university);
            message_jsonObj.put("message",a);
            response.getWriter().println(message_jsonObj);
        }catch (SQLException e) {
            message_jsonObj.put("message", "数据库异常");
            response.getWriter().println(message_jsonObj);
            e.printStackTrace();
        }catch (BysjException e){
            message_jsonObj.put("message","自定义异常");
            response.getWriter().println(message_jsonObj);
            e.printStackTrace();
        }catch (Exception e){
            message_jsonObj.put("message","网络异常");
            response.getWriter().println(message_jsonObj);
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
